package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.SetViewPropertiesReq;
import net.ib.mntalk.protocol.Session.GetViewPropertiesRes;
import net.ib.mntalk.protocol.Session.SetViewPropertiesRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.DatabaseContract.ViewTable;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;

public class SetViewPropertiesTask extends AsyncNetTask {

	private SetViewPropertiesReq mSetViewPropertiesReq;
	
	public SetViewPropertiesTask(Context context, Handler handler, SetViewPropertiesReq setViewPropertiesReq){
		super(context, handler);
		this.mSetViewPropertiesReq = setViewPropertiesReq;
	}
	
	@Override
	protected TcpEnvelope onPreExecute() {
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(mSetViewPropertiesReq)
			.setMethodId(Session.View.SetViewProperties)
			.build();
		return rev;
	}
	
	@Override
	protected void onPostExecute(int resultCode, Object sentObject,
			Object receivedObject) {
		MTalkLogWriter.d("SetViewPropertiesTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		SetViewPropertiesRes setViewPropertiesRes = (SetViewPropertiesRes) resultEnvelope.getMessage();
		
		if(setViewPropertiesRes.getResponseCode() == Common.SUCCESS){
			// 변경사항을 적용하자!
			for(int i = 0; i < mSetViewPropertiesReq.getPropertyCount(); i++){
				switch(mSetViewPropertiesReq.getProperty(i)){
					case Common.PUSH_ALLOWED:
						int PushAllowed;
						if(mSetViewPropertiesReq.getView().getPushAllowed()){
							PushAllowed = ViewTable.PushType.ON.ordinal();
						}else{
							PushAllowed = ViewTable.PushType.OFF.ordinal();
						}
						InboxDatabaseHelper.updateViewPushState(mContext, mSetViewPropertiesReq.getView().getViewUuid(), PushAllowed);
						break;
					case Common.TITLE:
						InboxDatabaseHelper.updateViewTitle(mContext, mSetViewPropertiesReq.getView().getViewUuid(), mSetViewPropertiesReq.getView().getTitle());
						break;
				}
			}
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_GET_VIEW_PROPERTIES_SUCCESS));
		} else{
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_GET_VIEW_PROPERTIES_FAIL));
		}
	}
}
